package com.study.rpc;

import com.study.rpc.entity.Request;
import com.study.rpc.entity.Response;

import java.io.*;
import java.net.Socket;

/**
 * @version V1.0
 * @title: SocketClient
 * @description: ${DESCRIPTION}
 * @author: wanghuilong
 * @date: 2019-11-11 17:30
 * @copyright: http://fingo.com.my/
 */
public class SocketClient {

    private Socket socket;

    public Object invoke(Request request, String Ip, int port) throws IOException {
        socket = new Socket(Ip, port);
        InputStream in = socket.getInputStream();
        OutputStream out = socket.getOutputStream();
        ObjectOutputStream objOut;
        ObjectInputStream objIn;
        Response response = new Response();
        try {
            objOut = new ObjectOutputStream(out);
            objOut.writeObject(request);
            objOut.flush();
            objIn = new ObjectInputStream(in);
            Object result = objIn.readObject();
            if (result instanceof Response) {
                response = (Response) result;
            } else {
                throw new RuntimeException("返回对象不正确");
            }

        } catch (Exception e) {
            System.out.println("error: " + e.getMessage());
        } finally {
            out.close();
            in.close();
            socket.close();
            return response.getData();
        }
    }

}
